<!DOCTYPE html>
<html>
  <head>
  <script type="text/javascript" src="freddygotfingered.js"></script>
  <script type="text/javascript" src="microformat.js"></script>
  <script type="text/javascript" src="hcard.js"></script>
  <script type="text/javascript" src="standardAPI.js"></script>
    <script>
      var webfinger;
      var profileInfo;
      var hasUpdatesFeed;
      var isFollowing = false;
      
      var standardAPI = new StandardAPI(localStorage["apiroot"], localStorage["token"]);

	  function startFollowing(target) {
		standardAPI.startFollowing(target);
	  }

	  function stopFollowing(target) {
		standardAPI.stopFollowing(target);
	  }
      
      // Called when a message is passed from the contentscript
      function onRequest(request, sender, sendResponse) {
        if (request.webfinger) {
          handleWebfinger(request.webfinger, sender.tab.id);
          // Return nothing to let the connection be cleaned up.
          sendResponse({});
        }
      };
      
      
      //  called when the url is changed
      //  hack to demonstrate the concept, since no one currently has the link on thier pages
      //  we are going to look for known url patterns, where we can figure out the webfinger.

      function checkForRecognizedUrl(tabId, changeInfo, tab) {
        var googleProfilesRegEx = new RegExp('^http(?:s)?://(?:www.)?google.com/profiles/(.*?)(?:#.*)?(?:/.*)?$');
        var identicaRegEx = new RegExp('^http(?:s)?://identi.ca/(.*?)(?:/.*)?$');
        var cliqsetRegEx = new RegExp('^http(?:s)?://(?:www.)?cliqset.com/(.*?)(?:/.*)?$');

        if (changeInfo.status == 'complete' && tab.url) {        
          var googleMatches = googleProfilesRegEx.exec(tab.url);
          if (googleMatches && googleMatches.length > 0) {
            handleWebfinger('acct:' + googleMatches[1] + '@gmail.com', tabId);
            return;
          }
          
          var identicaMatches = identicaRegEx.exec(tab.url);
          if (identicaMatches && identicaMatches.length > 0) {
            handleWebfinger('acct:' + identicaMatches[1] + '@identi.ca', tabId);
            return;
          }
          
          var cliqsetMatches = cliqsetRegEx.exec(tab.url);
          if (cliqsetMatches && cliqsetMatches.length > 0) {
            handleWebfinger('acct:' + cliqsetMatches[1] + '@cliqset.com', tabId);
            return;
          }
        }
      };

      function handleWebfinger(webfinger, tabId) {
          getWebfingerInfo(webfinger, function(profileInfo) {
            if (profileInfo) {
              isFollowing = standardAPI.isFollowing(webfinger.substring(5));
              chrome.pageAction.setPopup({tabId : tabId, popup: 'popup.html?webfinger=' + encodeURIComponent(webfinger.substring(5)) + '&thumbnailUrl=' + encodeURIComponent(profileInfo.entry.thumbnailUrl) + '&displayName=' + encodeURIComponent(profileInfo.entry.displayName) + '&profileUrl=' + encodeURIComponent(profileInfo.entry.profileUrl) + '&bio=' + encodeURIComponent(profileInfo.entry.note) + '&isFollowing=' + isFollowing});

              // Show the page action for the tab that the sender (content script) was on.
              chrome.pageAction.setTitle({tabId : tabId, title: webfinger});
              chrome.pageAction.show(tabId);
            }
          });
      }
      
      function getWebfingerInfo(webfinger, callback) {
        discover(webfinger, function(xrd) {
          console.log('discovering...(' + webfinger + ')');
          var profileInfo = null;
          
          var updatesFromHref = xrd.getByRel('http://schemas.google.com/g/2010#updates-from').attributes['href'].value;
          
          var pocoMeLink = xrd.getByRel('http://portablecontacts.net/spec/1.0#me');
          
          var hcardLink = xrd.getByRel('http://microformats.org/profile/hcard');
          
          if (pocoMeLink !== null) {
            //fetch the poco#me url
            _xhr = new XMLHttpRequest();
            _xhr.open("GET", pocoMeLink.attributes['href'].value, false);
            _xhr.send(null);
            profileInfo = JSON.parse(_xhr.responseText);
          }
          
          if (profileInfo !== null) { 
            callback(profileInfo); 
            return;
          }
          
          if (hcardLink !== null) {
            _xhr = new XMLHttpRequest();
            _xhr.open("GET", hcardLink.attributes['href'].value, false);
            _xhr.send(null);
            hcardDoc = new DOMParser().parseFromString(_xhr.responseText,"text/xml");
            var people = HCard.discover(hcardDoc.getElementsByTagName('html')[0]);
            if (people.length > 0) {
                profileInfo = { entry : { 'thumbnailUrl' : people[0].photoList[0], 'displayName' : people[0].fn, 'profileUrl' : people[0].urlList[0], 'note' : people[0].bio}};
                callback(profileInfo);
            }
          }
        });
      }

      // Listen for any changes to the URL of any tab.
      chrome.tabs.onUpdated.addListener(checkForRecognizedUrl);
      
      // Listen for the content script to send a message to the background page.
      chrome.extension.onRequest.addListener(onRequest);
    </script>
  </head>
</html>
